<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { passwordLoginAPI } from '@/apis/admin' 
import { useRouter } from 'vue-router'
import { useAdminStore } from '@/stores/admin' 


const form = ref({
  account: '',
  password: ''
})
const adminStore = useAdminStore()

const rules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const router = useRouter()

const handleLogin = async () => {
  // 验证表单
  if (form.value) {
    // 提交登录请求
    try {
          const formData = form.value
          const response = await passwordLoginAPI({
            account: formData.account,
            password: formData.password
          })
          // 存储登录状态和 token
          console.log(response.data.Authorization);
          adminStore.updateAdminInfo(response.data.userInfo)
          localStorage.setItem('admin_token', response.data.Authorization)
          localStorage.removeItem("user_token");
          ElMessage.success('登录成功')
          // 跳转到后台主页或其他页面
          router.push({ name: 'adminHome' }) // 使用路由名称确保正确跳转
        } catch (error) {
          // 处理登录失败
          console.error('Login failed:', error)
          // 清除登录状态和 token
          adminStore.updateAdminInfo(null)
          localStorage.removeItem('admin_token')
          // 显示错误消息
          ElMessage.error('登录失败，请检查用户名或密码')
        }
  }
}

</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 登录表单 -->
      <el-form  :model="form" :rules="rules" size="large" autocomplete="off">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="account">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item prop="password" >
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="handleLogin">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="router.push('/')">
            ← 返回首页
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
      url('@/assets/images/login-bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>